<?php

namespace App\Http\Controllers\Admin;

use App\Models\AnswerActivity;
use App\Models\AnswerActivityGift;
use App\Models\AnswerActivityGiftConfig;
use App\Models\AnswerActivityGiftTime;
use App\Validate\AnswerActivityGiftTimeValidate;

/**
 * 活动礼物排版管理
 */
class AnswerActivityGiftTimeController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityGiftTime();
        $this->validate = new AnswerActivityGiftTimeValidate();
    }

    /**
     * 列表
     * @param act_id int 活动id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     * @param type int 0或空表示  1文化红包 2精美礼品
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断是否可以添加礼物
        $activityGiftModel = new AnswerActivityGift();
        $isAllowAddGift = $activityGiftModel->isAllowAddGift($this->request->act_id);
        if ($isAllowAddGift !== true) {
            return $this->returnApi(202, $isAllowAddGift);
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $type = $this->request->type;
        $act_id = $this->request->act_id;

        $res = $this->model->lists(null, $act_id, $type, $start_time, $end_time, $page, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['type_name'] = $val['type'] == 1 ? '文化红包' : '精美礼品';
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 类型id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param act_id int活动id
     * @param start_time 奖品开始发放时间   
     * @param end_time 结束时间   和开始时间对应
     * @param type tinyint 奖品类型 1文化红包 2精美礼品
     * @param number int 发放数量
     * @param user_gift_number int 用户当日可获得多少礼品
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断是否可以添加礼物
        $activityGiftModel = new AnswerActivityGift();
        $isAllowAddGift = $activityGiftModel->isAllowAddGift($this->request->act_id);
        if ($isAllowAddGift !== true) {
            return $this->returnApi(202, $isAllowAddGift);
        }
        //判断时间是否叠加
        $isTimeOverlay = $this->model->isTimeOverlay($this->request->all());
        if (!empty($isTimeOverlay)) {
            return $this->returnApi(202, '您选择的时间和之前设置的时间有重叠，请重新选择');
        }

        $res = $this->model->add($this->request->all());

        if (!$res) {
            return $this->returnApi(202, "新增失败");
        }
        return $this->returnApi(200, "新增成功", true);
    }

    /**
     * 修改
     * @param id int 礼物公示id
     * @param start_time 奖品开始发放时间   
     * @param end_time 结束时间   和开始时间对应
     * @param type tinyint 奖品类型 1文化红包 2精美礼品
     * @param number int 发放数量
     * @param user_gift_number int 用户当日可获得多少礼品
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $result = $this->model->find($this->request->id);
        if (empty($result)) {
            return $this->returnApi(202, '参数传递错误');
        }
        //判断是否可以添加礼物
        $activityGiftModel = new AnswerActivityGift();
        $isAllowAddGift = $activityGiftModel->isAllowAddGift($result->act_id);
        if ($isAllowAddGift !== true) {
            return $this->returnApi(202, $isAllowAddGift);
        }
        //判断时间是否叠加
        $this->request->merge(['act_id' => $result->act_id]);
        $isTimeOverlay = $this->model->isTimeOverlay($this->request->all() , $this->request->id);
        if (!empty($isTimeOverlay)) {
            return $this->returnApi(202, '您选择的时间和之前设置的时间有重叠，请重新选择');
        }

        $res = $this->model->change($this->request->all());

        if (!$res) {
            return $this->returnApi(202, "修改失败");
        }
        return $this->returnApi(200, "修改成功", true);
    }

    /**
     * 删除
     * @param id int 类型id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }


    /**
     * 获取礼物发放总概率 
     * 标题为：礼品概率总配置
     * 1.概率模式：①  独立概率模式（默认）：选择后，显示当前最大概率是多少，最小概率是多少，不能改  
     *            ②  总概率模式：选择后，显示当前总概率是多少，但是不能改   （如果要设置，只能去礼物哪里单独设置）   
     * 2.红包每日最大发放数量 
     * 3.实物礼品每日最大发放数量
     * 4.用户每日获得红包最大数量 
     * 5.用户每日获得实物礼品每日最大数量
     * 备注：发放排版已设置的时间段，总配置无效
     * 
     * @param  act_id 活动id
     */
    public function getSendTotalConfig(){
        //增加验证场景进行验证
        if (!$this->validate->scene('get_send_total_config')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $activityGiftConfigModel = new AnswerActivityGiftConfig();
        $res = $activityGiftConfigModel
                    ->select('percent_way','gift_max_number_day','red_max_number_day','user_gift_number_day','user_red_number_day')
                    ->where('act_id', $this->request->act_id)
                    ->first();
        if(empty($res)){
            $res['percent_way'] = 0;
            $res['gift_max_number_day'] = null;
            $res['red_max_number_day'] = null;
            $res['user_gift_number_day'] = null;
            $res['user_red_number_day'] = null;
        }
        //获取总概率
        $activityGiftModel = new AnswerActivityGift();
        $res['total_percent'] = $activityGiftModel->where('act_id', $this->request->act_id)->where('is_del', 1)->sum('percent');
        $res['max_percent'] = $activityGiftModel->where('act_id' , $this->request->act_id)->where('is_del' , 1)->max('percent');
        $res['min_percent'] = $activityGiftModel->where('act_id' , $this->request->act_id)->where('is_del' , 1)->min('percent');


        return $this->returnApi(200, "获取成功", true , $res);
    }


    /**
     * 设置礼物发放总概率 
     * 标题为：礼品概率总配置
     * 1.概率模式：①  独立概率模式（默认）：选择后，显示当前最大概率是多少，最小概率是多少，不能改  
     *            ②  总概率模式：选择后，显示当前总概率是多少，但是不能改   （如果要设置，只能去礼物哪里单独设置）   
     * 2.红包每日最大发放数量 
     * 3.实物礼品每日最大发放数量
     * 4.用户每日获得红包最大数量 
     * 5.用户每日获得实物礼品每日最大数量
     * 备注：发放排版已设置的时间段，总配置无效
     * 
     * @param  act_id 活动id
     * @param  percent_way 概率方式   1 单个奖品独立概率方式    2 所以奖品总概率形式
     * @param  gift_max_number_day 礼物每日发送奖品最大数量
     * @param  red_max_number_day 红包每日发送奖品最大数量
     * @param  user_gift_number_day 用户当日可获得多少实物礼品
     * @param  user_red_number_day 用户当日可获得多少红包礼品
     */
    public function setSendTotalConfig(){
        //增加验证场景进行验证
        if (!$this->validate->scene('set_send_total_config')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //如果活动开始，就允许修改活动
        $activityInfo = AnswerActivity::where('id', $this->request->act_id)->first();
        if(empty($activityInfo)){
            return $this->returnApi(201, '活动不存在');
        }
        $activityGiftConfigModel = new AnswerActivityGiftConfig();
        $res = $activityGiftConfigModel->where('act_id', $this->request->act_id)->first();
        if($activityInfo['start_time'] <= date('Y-m-d H:i:s') && !empty($res) && $res->percent_way != $this->request->percent_way){
            return $this->returnApi(201, '活动已开始，不能修改概率模式，只能修改数量');
        }



        //判断总概率，不能超过100
        if($this->request->percent_way == 2){
           $total_percent = $activityGiftConfigModel->getActTotalPercent($this->request->act_id);
           if($total_percent > 100){
                return $this->returnApi(201, '活动总概率超过100%，不能设置为所有奖品总概率方式，若要设置，请先修改奖品概率');
           }
        }
     

        if(empty($res)){
            $res = $activityGiftConfigModel;
        }
        $res->act_id = $this->request->act_id;
        $res->percent_way = $this->request->percent_way;
        $res->gift_max_number_day = $this->request->gift_max_number_day;
        $res->red_max_number_day = $this->request->red_max_number_day;
        $res->user_gift_number_day = $this->request->user_gift_number_day;
        $res->user_red_number_day = $this->request->user_red_number_day;
        $result =  $res->save();

        if ($result) {
            return $this->returnApi(200, "设置成功", true);
        }
        return $this->returnApi(202, '设置失败');
    }




}
